// pages/Personal_matches/createpersonalmatch/create.js
const app = getApp()
const socketUrl = app.globalData.socketHost
var socketStatus = 'closed'
import { getPlayList, getPlayerQR, getBillno, createMatch, addPlayer, getCourseList } from '../../../http/game'
Page({

    /**
     * 页面的初始数据
     */
    data: {
        staticUrl: app.globalData.staticUrl,
        watch_typelists: [{
            name: '私密',
            value: '0'
        },
        {
            name: '公开',
            value: '1',
            checked: 'true'
        },
        {
            name: '好友公开',
            value: '2'
        },
        ],
       
        playList: [],
        MAX_players: 4,
        players_info: [],
        course_name: "请选择球场",
        match_date: "",
        matchplayqrcode: "",
        error: "",
        playChecked: [],
        match_billno: "",
        creatmatchdata: {
            cr_hole: "",
            match_name: "",
            course_id: "",
            match_date: "",
            // 默认值同watch_typelists列表中默认选中的值相对应
            watch_type: "1",
            // 默认值同bet_typelists列表中默认选中的值相对应
            bet_type: "1",
            play_id: 0,
            player_ids: {},
            match_billno: "",
        },
        today: "",
        isopencal: false,
        userInfo: {},
        QrcodeUrl: "",
        isMyMatch: true
    },


    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: async function (options) {
        var today = new Date().toLocaleDateString();
        const my_id = app.globalData.userInfo.player_id
        this.setData({
            today,
            match_date: today,
            my_id
        });
        const player = {};
        const userInfo = app.globalData.userInfo;
        const players_info = []
        player.player_id = userInfo.player_id;
        player.headimg = userInfo.avatarUrl;
        player.player_name = userInfo.nickName;
        player.isOwner = true;
        this.data.creatmatchdata.match_name = userInfo.nickName + "-记分卡"
        players_info.push(player);
        this.setData({
            players_info,
            userInfo,
            creatmatchdata: this.data.creatmatchdata
        });

        const eventChannel = this.getOpenerEventChannel()
        if (eventChannel) {
            eventChannel.on('acceptData', (data) => {
                data.players_info.forEach(player => {
                    this.addPlayer(player)
                })
                this.setData({
                    'creatmatchdata.course_id': data.course_id,
                    course_name: data.course_name,
                })
            })
        }
        this.getCourseList()
        this.getData();
    },
    onShow: function (course) {
        if (!!course) {
            this.setData({
                'creatmatchdata.cr_hole': course.cr_hole,
                'creatmatchdata.course_id': course.course_id,
                course_name: course.course_name,
                course: course
            })
        } else return
            
    },
    onReady: function () {
        //获得popup组件
        this.popup = this.selectComponent("#popup");
        this.popupCalendar = this.selectComponent("#popupCalendar");
    },
    opencal: function () {
        this.popupCalendar.showPopup();
    },

    //组件监听事件
    select(e) {
        this.setData({
            match_date: e.detail,
            'creatmatchdata.match_date': e.detail
        })
    },

    async getData() {
      // 获取球局单号
      var player_id = this.data.userInfo.id;
      getBillno({player_id}).then(res => {

        this.setData({
            match_billno: res.data,
            'creatmatchdata.match_billno': res.data
        })
      })
    
        
    },
    async getCourseList() {
        let course = null
        const { course_id } = this.data.creatmatchdata
        const location = wx.getStorageSync('location')
        const { data } = await getCourseList(location)
        if (course_id) {
            course = data.list.filter(item => item.course_id == course_id)[0] || null
        } else {
            course = data.near.length > 0 ? data.near[0] : null
        }
        this.setData({
            course_name: course.course_name || '请选择球场',
            'creatmatchdata.course_id': course.course_id || '',
            course
        })
    },
    // 显示添加球员
    showPlayersPopup() {
        this.selectComponent("#popup-player").showPopup();
    },
    //取消事件
    _successPlayer() {
        this.selectComponent("#popup-player").hidePopup();
    },
    showPopup() {
        this.popup.showPopup();
    },
    _errorcal() {
        this.popupCalendar.hidePopup();
    },

    //错误消息
    _errorshow: function (msg) {
        this.setData({
            error: ''
        });
        this.setData({
            error: msg
        })
    },

    _addPlayer:function(e) {
        this._successPlayer();
        if(e.detail && e.detail.pl_id){
            this.addPlayer(e.detail); 
        }
    },
    //二维码取消事件
    _error() {
        this.popup.hidePopup();
    },
    //确认事件
    _success() {
        this.popup.hidePopup();
    },
    _errorHalf() {
        this.selectComponent("#popup-half").hidePopup();
    },
    _successHalf(e) {
        this.setData({
            'creatmatchdata.cr_hole': e.detail.cr_hole
        })
        this.selectComponent("#popup-half").hidePopup()
    },
    // 下一步
    creatematchplay: async function (e) {
        const data = this.data.creatmatchdata
        if (!data.cr_hole) {
            this.selectComponent("#popup-half").showPopup()
            return
        }
        const { players_info, creatmatchdata, match_billno,userInfo } = this.data
        let playersstr = '';
        for (let key in players_info) {
            playersstr += players_info[key].player_id+',';
        }
        if(playersstr){
            playersstr = playersstr.substr(0,playersstr.length-1);
        }
        creatmatchdata.lists = playersstr;
        console.log(playersstr);
        // 创建比赛接口
        await createMatch({cr_hole: creatmatchdata.cr_hole,
            match_name:  creatmatchdata.match_name,
            course_id:  creatmatchdata.course_id,
            match_date:  creatmatchdata.match_date,
            watch_type: creatmatchdata.watch_type,
            bet_type: creatmatchdata.bet_type,
            play_id: creatmatchdata.play_id,
            lists: creatmatchdata.lists,
            match_billno:  creatmatchdata.match_billno,
            player_id:userInfo.player_id,
        }).then(async (res) => {
           /* // 添加球员
            await addPlayer({
                match_billno,
                player_ids: playersstr.toString()
            })*/
            const players_info = {
                player_id: userInfo.player_id,
                avatarUrl: userInfo.avatarUrl,
                nickName: userInfo.nickName
            }
            wx.showToast({
                title: res.info,
                icon: 'none',
                complete: () => {
                    console.log(res);
                   this.sendMessage({ status: 'success', code: 2, ids: playersstr, match_id: res.data, match_billno,players_info:players_info});
                   
                    wx.redirectTo({
                        url: `/pages/Personal_matches/match/match?match_id=${res.data}&pm_billno=${match_billno}`
                    })
                }
            })
        })
    },

    // changePlaylists: function(e) {
    //     const checkedList = e.detail.value;
    //     let { playList, playChecked } = this.data
    //     playList.forEach(item => {
    //         if (checkedList.includes(item.play_id.toString())) {
    //             item.checked = true
    //         } else {
    //             item.checked = false
    //         }
    //     })
    //     playChecked = playList.filter(item => item.checked == true)
    //     this.setData({
    //         playChecked: playChecked,
    //         'creatmatchdata.play_id': checkedList.join(',')
    //     });
    // },
    inputvalue: function (e) {
        this.setData({
            'creatmatchdata.match_name': e.detail.value
        })
    },
    scanplayerqrcode: function () {
        wx.scanCode({
            success: (res) => {
                console.log("扫码结果:", res);
                this.setData({
                    img: res.result
                })
            },
            fail: (res) => {
                console.log(res);
            }
        })
    },

    openQrcode: async function () {
        const { course_id, match_billno, } = this.data.creatmatchdata
        const {userInfo} = this.data;
        const res = await getPlayerQR({type:1, c: course_id, match_billno,pl_id: userInfo.player_id})
        //console.log(res);
        this.setData({
            QrcodeUrl: res,
        });
        this.websocketGame()
        this.showPopup();
    },
    deleteplayer: function (e) {
        var index = e.currentTarget.dataset.index;
        let { players_info, match_billno } = this.data;
        const send_id = players_info[index].player_id
        players_info.splice(index, 1);
        this.setData({
            players_info: players_info
        });
        this.sendMessage({ id: send_id, match_billno, status: 'delete success', code: 3 });
    },

    addPlayer(player) {
       // var players_info = this.data.players_info;
       

        let{players_info} = this.data;
        if (players_info.length >= 4) {
            this._errorshow("一组不能超过4人");
            return;
        }
        console.log(players_info);
        console.log(player);
        var playerres = players_info.filter(item=>{return item.player_id == player.pl_id});
        if(playerres && playerres.length>0){
           wx.showToast({
             title: '球员已在球局',
             icon:'error',
           })
           return ;
        }

        var players_info_item = {};
        players_info_item.player_id = player.pl_id;
        players_info_item.headimg = player.avatarUrl;
        players_info_item.player_name = player.nickName;
        players_info_item.isOwner = false;
        players_info.push(players_info_item);

        this.setData({
            players_info: players_info
        });
    },

    toAddPlayer(e) {
        const type = e.currentTarget.dataset
        const params = type ? '?type=true' : ''
        wx.navigateTo({
            url: '/pages/index/gamelist/history/history' + params,
            events: {
                // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
                acceptDataFromOpenedPage: function (data) {
                    console.log(data)
                },
                someEvent: function (data) {
                    console.log(data)
                }
            },
            success: (res) => {
                // 通过eventChannel向被打开页面传送数据
                res.eventChannel.emit('acceptDataFromOpenerPage', {
                    players_info: this.data.players_info,
                })
            }
        })
    },

    // 选择观战方式
    radioChangeWatch(data) {
        this.setData({
            'creatmatchdata.watch_type': data.detail.value
        })
    },
    // 选择押注设置
    radioChangeBet(data) {
        this.setData({
            'creatmatchdata.bet_type': data.detail.value
        })
    },
    // 跳转到选择城市
    area_selcet() {
        wx.navigateTo({
            url: '/pages/Personal_matches/area/area'
        });
    },
    websocketGame() {
        if (socketStatus === 'closed') {
            this.openSocket();
        }
    },
   
    onUnload() {
       // this.sendMessage({ status: 'closed', code: 0 })
        this.closeSocket()
    },
    onShareAppMessage: function (e) {
        if (e.from === 'button') {
            const { match_date, course_id, match_billno } = this.data.creatmatchdata
            const {userInfo} = this.data;
            console.log(userInfo);
            this._successPlayer()
            this.websocketGame()
            console.log(`/pages/Personal_matches/friend/friend?match_billno=${match_billno}&id=${userInfo.player_id}&time=${match_date}&c=${course_id}`);
            return {
                title: '',
                path: `/pages/Personal_matches/friend/friend?match_billno=${match_billno}&id=${userInfo.player_id}&time=${match_date}&c=${course_id}`
            }
        }
        return {}
    },


    
//处理消息的方法
websocketGame() {
    this.closeSocket();
    this.openSocket();

},
  /**** socket *****/
  openSocket() {
    let{match_billno} = this.data;
    const {nickName , player_id, avatarUrl } =app.globalData.userInfo
          const players_info = {
              player_id: player_id,
              headimg: avatarUrl,
              player_name: nickName
          }
          const params = {
              
              players_info: players_info, //我的信息
              match_billno:match_billno,
          }
          var that = this;
          var timer = setInterval(function() {
              app.websocketrevice(params,function(res) {
                      if(res.data){
                          that.handleSocket(res.data.data);
                      }
              },function() {
  
              })
          },10000);
              this.setData({timer});
  },
  //关闭信道
  closeSocket() {
    if(this.data.timer){
      clearInterval(this.data.timer);
    }
  },
  //发送消息函数
  sendMessage(params) {
    console.log(params,'发送消息');
      app.websocketsend(params,function(res) {
         
      },function() {
  
      })
 
  },
  
  // // 处理socket 
  handleSocket(response) {
    const { my_id, match_billno, match_id ,players_info} = this.data
    if (response.type=='join'  && response.match_billno === match_billno) {
        console.log(response)
        if(response.players_info){
         
         // 是否是本人球局
        const players = players_info.map(item => {
        return item.pl_id
        })
         var  isInmatch = players.includes(response.players_info.player_id);
          if(isInmatch) //已经在组里面了
          {
            this.sendMessage({ type: 'join', code: 4,match_billno: match_billno,players_info:response.players_info }); //发送已经存在的消息给对方
            return ;
          }

          this.addPlayer(response.players_info);
       
              //二维码取消事件
         this.popup.hidePopup();
          this.sendMessage({  type: 'join', code: 1, match_billno: match_billno,players_info:response.players_info});
        }
       
         
     }
  },
})